package cn.tk.utils.snowflake;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.net.Inet4Address;
import java.net.UnknownHostException;

/**
 * Created by denglw on 2019/9/11.<br/>
 * Desc: 主键ID生成器配置类
 */
@Slf4j
@Configuration
public class IdWorkerConfig {

    /**
     * 获取ID生成器实例, 数据中心ID暂固定为0.<br/>
     */
    @Bean @Primary
    public IdWorker idWorker() {
        return new IdWorker(workerId(), 0);
    }

    /**
     * 获取机器ID, 降低冲突的概率.<br/>
     * @return long
     */
    private long workerId() {
        try {
            String address = Inet4Address.getLocalHost().getHostAddress();
            int[] ints = StringUtils.toCodePoints(address);
            int sums = 0;
            for (int b : ints) {
                sums += b;
            }
            return (long) (sums % 32);
        } catch (UnknownHostException e) {
            // 如果获取失败，则使用随机数备用
            return RandomUtils.nextLong(0, 31);
        }
    }

}
